﻿using System;

namespace MvcApplication1.Tests 
{
    using Jurassic;

    using NUnit.Framework;

    public class JurassicTestHelper : IDisposable 
    {
        private ScriptEngine scriptEngine;

        /// <summary>
        /// You need to use this helper with Unit Tests and not 
        /// Basic Unit Tests because you need a Test Context
        /// </summary>
        public JurassicTestHelper() 
        {
            this.scriptEngine = new ScriptEngine();
            this.scriptEngine.CompatibilityMode = CompatibilityMode.ECMAScript3;
            this.scriptEngine.EnableDebugging = true;
        }

        /// <summary>
        /// Load the contents of a JavaScript file into the 
        /// Script Engine.
        /// </summary>
        /// <param name="path">Path to JavaScript file</param>
        public void LoadFile(string path)
        {
            this.scriptEngine.ExecuteFile(path);
        }

        /// <summary>
        /// Pass the path of the test that you want to execute.
        /// </summary>
        /// <param name="testMethodName">JavaScript function name</param>
        public object ExecuteTest(string testMethodName) 
        {
            try
            {
                return this.scriptEngine.CallGlobalFunction(testMethodName);
            }
            catch (JavaScriptException ex)
            {
                throw new AssertionException(ex.Message);
            }
        }

        public void Dispose()
        {
            this.scriptEngine = null;
        }
    }
}
